package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.CourseData;
import com.ycsj.goldmedalnewconcept.bean.CourseInfo;
import com.ycsj.goldmedalnewconcept.bean.CourseInfo.Data;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.fragment.CourseFragment;
import com.ycsj.goldmedalnewconcept.utils.IndicatorManager;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.magicindicator.MagicIndicator;
import com.ycsj.goldmedalnewconcept.view.supervp.SuperViewPager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



/**
 * 课程进度界面
 */
@SuppressLint("NewApi")
public class CourseProgressActivity extends FragmentActivity {

	
    //返回
    LinearLayout llBack;
    //标题
    TextView tvTitle;

    //导航条
    MagicIndicator indicator;

    //VP
    SuperViewPager superVp;

    //进度条
    LinearLayout llLoading;


    //Tab的标题集合
    private String[] mTites = {"1-1", "1-2", "1-3", "1-4"};


    //教室classnum
    private String classNum;

    //ViewPager的Framgent集合
    private List<Fragment> mFramgents;
    private VpAdapter adapter;
    private Intent intent;
    private String userID;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_courseprogress);
        intent = getIntent();
        classNum = intent.getStringExtra("class_id");
        
        
        userID = SPUtil.getString(this, "account", "");
        //设置6.0以后沉浸状体栏的问题
        setBar();

        initView();

        initListener();

        getIntentData();

        initMag();

        initData();

        http();
    }


    /**
     * 初始化View方法
     */
    private void initView() {
        llBack = (LinearLayout) findViewById(R.id.ll_back);
        indicator = (MagicIndicator) findViewById(R.id.mag);
        superVp = (SuperViewPager) findViewById(R.id.vp);
        llLoading = (LinearLayout) findViewById(R.id.ll_loading);
    }

    /**
     * 设置监听的方法
     */
    private void initListener() {
        llBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    /**
     * 获取页面传递过来的值
     */
    public void getIntentData() {

    }

    /**
     * 初始化导航条的方法
     */
    private void initMag() {
        IndicatorManager.setIndicator(this, 5, indicator, superVp, mTites, getResources().getColor(R.color.white), getResources().getColor(R.color.white), null);
    }

    /**
     * 初始化页面数据,这列需要请求服务器来获取数据
     */
    private void initData() {
        mFramgents = new ArrayList<Fragment>();
    }

    /**
     * 网络请求的方法
     */
    private void http() {
    	
    	OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "17");
		builder.add("userID", userID);
		builder.add("classnum", classNum);
		// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=22&c=13006314760&role=2&userclass=1253
		Request request = new Request.Builder()
				.url(Constant.servlet_MessageController).post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				
				Gson gson = new Gson();
				String json = arg0.body().string();
				CourseData courseData = gson.fromJson(json,
						CourseData.class);
				Log.e("test", json);
				  try {
	                    if (null != courseData) {
	                        final List<Integer> unit = courseData.getUnit();
	                        
	                        runOnUiThread(new Runnable() {
	        					@Override
	        					public void run() {
	        						llLoading.setVisibility(View.GONE);
	        					}
	        				});
	                        
	                        runOnUiThread(new Runnable() {
            					@Override
            					public void run() {
            				
	                        for (int i = 0; i < 4; i++) {
	                            CourseInfo info = new CourseInfo();
	                            List<CourseInfo.Data> datas = new ArrayList<Data>();
	                            //添加4个Framgent
	                            for (int j = i * 18; j < (i + 1) * 18; j++) {
	                                final CourseInfo.Data data = info.new Data();
	                                if (null != unit && unit.size() != 0) {
	                                    if (unit.contains(j+1)) {
	                                        data.setFlag(true);
	                                    }
	                                } else {
	                                    data.setFlag(false);
	                                }
	                                data.setName("Unit" + (j + 1));
	                                datas.add(data);
	                            }
	                            info.setmDatas(datas);
	                            CourseFragment fragment = new CourseFragment();
	                            Bundle bundle = new Bundle();
	                            bundle.putSerializable("data", info);
	                            fragment.setArguments(bundle);
	                            mFramgents.add(fragment);

	                            //初始化ViewPager控件
	                            initVp();
	                        }

            					}
            				});
	                        
	                        
	                        
	                    }
	                } catch (Exception e) {
	                    e.printStackTrace();
	                    Toast.makeText(CourseProgressActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
	                }

			}
		});
//        //获取服务器数据
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("type", "17");
//        map.put("userID", "13006314760");
//        map.put("classnum", classNum);
//
//        OkHttpUtils.post().url("http://139.129.213.183/ycsj_jpxgn/servlet/MessageController").params(map).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                if (null != llLoading) {
//                    llLoading.setVisibility(View.GONE);
//                }
//                Toast.makeText(CourseProgressActivity.this, "网络层错误", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onResponse(String s, int pos) {
//                try {
//                    CourseData courseData = GsonUtil.jsonToBean(s, CourseData.class);
//                    if (null != courseData) {
//                        List<Integer> unit = courseData.getUnit();
//                        llLoading.setVisibility(View.GONE);
//                        for (int i = 0; i < 4; i++) {
//                            CourseInfo info = new CourseInfo();
//                            List<CourseInfo.Data> datas = new ArrayList<Data>();
//                            //添加4个Framgent
//                            for (int j = i * 18; j < (i + 1) * 18; j++) {
//                                CourseInfo.Data data = info.new Data();
//                                if (null != unit && unit.size() != 0) {
//                                    if (unit.contains(j)) {
//                                        data.setFlag(true);
//                                    }
//                                } else {
//                                    data.setFlag(false);
//                                }
//                                data.setName("Unit" + (j + 1));
//                                datas.add(data);
//                            }
//                            info.setmDatas(datas);
//                            CourseFragment fragment = new CourseFragment();
//                            Bundle bundle = new Bundle();
//                            bundle.putSerializable("data", info);
//                            fragment.setArguments(bundle);
//                            mFramgents.add(fragment);
//
//                            //初始化ViewPager控件
//                            initVp();
//                        }
//
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    Toast.makeText(CourseProgressActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//        });

    }

    /**
     * 设置ViewPager
     */
    private void initVp() {
        adapter = new VpAdapter(getSupportFragmentManager());
        superVp.setAdapter(adapter);
        superVp.setOffscreenPageLimit(mFramgents.size());
    }


    /**
     * ViewPager的适配器
     */
    public class VpAdapter extends FragmentStatePagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFramgents.get(position);
        }

        @Override
        public int getCount() {
            return mFramgents.size();
        }
    }


    /**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    private void setBar() {
        //兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            //为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }

}
